package www.woniuxy.com.class112.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import www.woniuxy.com.class112.dao.*;
import www.woniuxy.com.class112.dto.*;
import www.woniuxy.com.class112.entity.*;
import www.woniuxy.com.class112.param.*;
import www.woniuxy.com.class112.param.workOrdes.AdminselectWorkOrdersParam;
import www.woniuxy.com.class112.service.WorkOrdersService;
import www.woniuxy.com.class112.util.AliyunOSSUtil;
import www.woniuxy.com.class112.util.workOrderNumberUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WorkOrdersServiceImpl implements WorkOrdersService {

    @Resource
    private SpecialAgentsMapper specialAgentsMapper;

    @Resource
    private AliyunOSSUtil ossUtil;
    @Resource
    private WorkOrdersMapper workOrdersMapper;

    @Resource
    private WorkVarietiesMapper workVarietiesMapper;
    @Resource
    private IssueTypeMapper issueTypeMapper;
    @Resource
    private IssuesMapper issuesMapper;
    @Resource
    private UserInfosMapper userInfosMapper;
    @Resource
    private WorkAgentImageMapper workAgentImageMapper;
    @Resource
    private WorkEntourageMapper workEntourageMapper;

    @Resource
    private WorkTechnologyMapper workTechnologyMapper;
    @Resource
    private WorkOrderDetailsMapper workOrderDetailsMapper;
    @Resource
    private WorkUserImageMapper workUserImageMapper;
    @Resource
    private ElasticsearchRestTemplate esTemplate;
    @Override
    public QusDto agriculturalIssues(AgriculturalIssuesParam param) throws Exception {
        UserInfos userInfos = userInfosMapper.selectByPrimaryKey(param.getUserId());
        if (userInfos==null)throw new Exception("当前用户不存在");
        if (userInfos.getRoleId()!=4L)throw new Exception("当前提问者不是用户");
        Issues issues = BeanUtil.toBean(param, Issues.class);
        issues.setTime(new Date());
        issues.setIssueState(0L);
        issues.setIssueNumber(workOrderNumberUtil.generateRandomCode());
        issuesMapper.insert(issues);
        for (MultipartFile multipartFile : param.getImage()) {
            String type = FileTypeUtil.getType(multipartFile.getInputStream());
            if (!"jpg".equals(type)&&!"png".equals(type)){
                throw new Exception("文件类型错误");
            }
            IssueType issueType = issueTypeMapper.selectByPrimaryKey(param.getIssueType());
            if (issueType==null){
                throw new Exception("类别不存在");
            }
            String name = multipartFile.getOriginalFilename();
            String substring = name.substring(name.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+ substring;
            String imageUrl = ossUtil.uploadFile(multipartFile.getInputStream(), fileName, "amour520");
            WorkUserImage workUserImage = new WorkUserImage();
            workUserImage.setIssueId(issues.getId());
            workUserImage.setUserId(param.getUserId());
            workUserImage.setIssueId(issues.getId());
            workUserImage.setUserImage(imageUrl);
            workUserImageMapper.insert(workUserImage);
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery= QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.matchQuery("title",param.getDescription()));
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 1));//页码从0开始
        NativeSearchQuery query = nativeSearchQueryBuilder.build();
        IndexCoordinates index = IndexCoordinates.of("qus");
        SearchHits<Qus> search = esTemplate.search(query, Qus.class, index);
        Qus qus = search.getSearchHits().get(0).getContent();
        if (qus==null)throw new Exception("当前未找到相关知识，请找特派员进行询问");
        QusDto qusDto = BeanUtil.toBean(qus, QusDto.class);
        qusDto.setIssuesId(issues.getId());
        return qusDto;
    }

    @Override
    public List<Issues> userQueryQuestionTable(Long userId,Long issueState) throws Exception {
        UserInfos userInfos = userInfosMapper.selectByPrimaryKey(userId);
        if (userInfos==null)throw new Exception("当前用户不存在");
        if (userInfos.getRoleId()!=4L)throw new Exception("当前查询者不是用户");
        List<Issues> issues =issuesMapper.all(userId);
        System.out.println(issues.isEmpty());
        if(issues==null||issues.isEmpty()){
            throw new Exception("当前用户并未向特派员提出过任何问题");
        }
        ArrayList<Issues> issues1 = new ArrayList<>();
        for (Issues issue : issues) {
            if (issue.getIssueState().longValue()==issueState.longValue()){
                issues1.add(issue);
            }
        }
        if (issues1==null||issues1.isEmpty())throw new Exception("当前用户并未有该数据，可能还在进行中");
        return issues1;
    }

    @Override
    public void specialEnvoyAcceptsOrders(specialEnvoyAcceptsOrdersParam param) throws Exception {
        Issues issues = issuesMapper.selectByPrimaryKey(param.getIssuesId());
        if (issues==null) throw new Exception("当前问题表不存在");
        if (issues.getIssueState().longValue()==2L)throw new Exception("当前问题已被知识库解决，无法向特派员发起请求");
        UserInfos userInfos = userInfosMapper.selectByPrimaryKey(param.getUserId());
        if (userInfos==null)throw new Exception("当前用户不存在");
        UserInfos userInfos1 = userInfosMapper.selectByPrimaryKey(param.getAgentId());
        if (userInfos1==null)throw new Exception("当前特派员不存在");
        WorkOrders workOrders = new WorkOrders();
        workOrders.setWorkNumber(issues.getIssueNumber());//工单编号
        workOrders.setStateId(1L);//1待评价2已评价
        workOrders.setIssueId(param.getIssuesId());//问题表的id
        workOrders.setAgentId(param.getAgentId());//处理工单的特派员
        workOrders.setCreatedDate(new Date());//创建时间
//        workOrders.setExpectedDate(param.getExpectedDate());//期望时间
        workOrders.setWorkResult(1L);//0取消处理1处理中2已解决
//        workOrders.setWorkType(2L);//1线上解决2线下解决
        workOrders.setOrderTitle(param.getOrderTitle());//工单标题
        workOrders.setIssueTypeId(issues.getIssueType());//问题表的类别id
        workOrders.setUserId(issues.getUserId());
        workOrdersMapper.insert(workOrders);
        issues.setIssueState(1L);//0.待办理1.处理中2.已解决3.未解决
        issues.setAgentId(param.getAgentId());//特派员id
        issues.setOrderId(workOrders.getId());//工单id
        issues.setResolvePeople(1L);//0知识库解决问题1特派员解决问题
        issuesMapper.updateByPrimaryKey(issues);
//        for (Long aLong : param.getAccompanyingId()) {//添加随行人员
//            WorkEntourage workEntourage = new WorkEntourage();
//            workEntourage.setAgentId(aLong);
//            workEntourage.setWorkId(workOrders.getId());
//            workEntourageMapper.insert(workEntourage);
//        }
    }

    @Override
    public void fillInTheWorkOrderAddress(FillInTheWorkOrderAddressParam param) throws Exception {
        UserInfos userInfos = userInfosMapper.selectByPrimaryKey(param.getUserId());
        if (userInfos==null)throw new Exception("当前登录用户不存在");
        Issues issues = issuesMapper.selectByPrimaryKey(param.getIssuesId());
        if (issues==null)throw new Exception("当前订单不存在");
        System.out.println(param.getUserId());
        if (issues.getUserId().longValue()!= param.getUserId().longValue())throw new Exception("当前登录用户不是提问者");
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(issues.getOrderId());
        if (workOrders==null)throw new Exception("当前工单不存在");
        workOrders.setWorkAddress(param.getWorkAddress());
        workOrdersMapper.updateByPrimaryKey(workOrders);//更新工单地址
    }

    @Override
    public void knowledgeBaseSolvesProblems(Long issuesId,Long userId) {
        System.out.println(issuesId);
        Issues issues = issuesMapper.selectByPrimaryKey(issuesId);
        issues.setResolvePeople(0L);//0知识库解决问题1特派员解决问题
        issues.setIssueState(2L);//0.待办理1.处理中2.已解决3.未解决
        WorkOrders workOrders = new WorkOrders();
        workOrders.setUserId(userId);
        workOrders.setWorkNumber(issues.getIssueNumber());//工单编号
        workOrders.setIssueId(issuesId);//问题id
        workOrders.setIssueTypeId(issues.getIssueType());
        workOrders.setCreatedDate(new Date());
        workOrders.setCompletionDate(new Date());
        workOrders.setOrderTitle(issues.getDescription());
        workOrders.setWorkResult(2L);
        workOrders.setStateId(1L);//1待评价2已评价
        workOrders.setWorkType(1L);
        workOrdersMapper.insert(workOrders);
        issues.setOrderId(workOrders.getId());
        issuesMapper.updateByPrimaryKey(issues);
    }

    @Override
    public void completeTheWorkOrder(CompleteTheWorkOrderParam param) throws Exception {
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(param.getId());
        workOrders.setCompletionDate(param.getCompletionDate());
        workOrders.setFeedback(param.getFeedback());
        workOrders.setNumberOfTrainees(param.getNumberOfTrainees());
        workOrders.setSolveTheProblem(param.getSolveTheProblem());
        workOrders.setWorkResult(2L);
        workOrders.setStateId(1L);//1待评价2已评价
        workOrders.setWorkType(2L);
        Issues issues = issuesMapper.selectByPrimaryKey(workOrders.getIssueId());
        issues.setResolvePeople(1L);//0知识库解决问题1特派员解决问题
        issues.setIssueState(2L);//0.待办理1.处理中2.已解决3.未解决
        issuesMapper.updateByPrimaryKey(issues);
        workOrdersMapper.updateByPrimaryKey(workOrders);

//        for (MultipartFile multipartFile : param.getImage()) {
//            String type = FileTypeUtil.getType(multipartFile.getInputStream());
//            if (!"jpg".equals(type)&&!"png".equals(type)){
//                throw new Exception("文件类型错误");
//            }
//            String name = multipartFile.getOriginalFilename();
//            String substring = name.substring(name.lastIndexOf("."));
//            String fileName = UUID.randomUUID().toString()+ substring;
//            String imageUrl = ossUtil.uploadFile(multipartFile.getInputStream(), fileName, "amour520");
//            WorkAgentImage workAgentImage = new WorkAgentImage();
//            workAgentImage.setAgentImage(imageUrl);
//            workAgentImage.setWorkId(param.getId());
//            workAgentImage.setAgentId(param.getAgentId());
//            workAgentImageMapper.insert(workAgentImage);
//        }
//        if (!param.getTechnologyId().isEmpty()){
//            for (Long aLong : param.getTechnologyId()) {
//                WorkTechnology workTechnology = new WorkTechnology();
//                workTechnology.setWorkId(param.getId());
//                workTechnology.setTechnologyId(aLong);
//                workTechnologyMapper.insert(workTechnology);
//            }
//        }
//        if (!param.getVarietiesId().isEmpty()){
//            for (Long aLong : param.getVarietiesId()) {
//                WorkVarieties workVarieties = new WorkVarieties();
//                workVarieties.setVarietiesId(aLong);
//                workVarieties.setWorkId(param.getId());
//                workVarietiesMapper.insert(workVarieties);
//            }
//        }
    }

    @Override
    public List<SpecialEnvoyQueriesWorkOrdersDto> specialEnvoyQueriesWorkOrders(Long agentId) {
        ArrayList<SpecialEnvoyQueriesWorkOrdersDto> specialEnvoyQueriesWorkOrdersDtos = new ArrayList<SpecialEnvoyQueriesWorkOrdersDto>();
        WorkOrdersExample workOrdersExample = new WorkOrdersExample();
        WorkOrdersExample.Criteria criteria = workOrdersExample.createCriteria();
        criteria.andAgentIdEqualTo(agentId);
        List<WorkOrders> workOrders = workOrdersMapper.selectByExample(workOrdersExample);
        for (WorkOrders workOrder : workOrders) {
            SpecialEnvoyQueriesWorkOrdersDto specialEnvoyQueriesWorkOrdersDto = BeanUtil.toBean(workOrder, SpecialEnvoyQueriesWorkOrdersDto.class);
            UserInfos userInfos = userInfosMapper.selectByPrimaryKey(agentId);
            specialEnvoyQueriesWorkOrdersDto.setAgentName(userInfos.getUserName());
            IssuesExample issuesExample = new IssuesExample();
            IssuesExample.Criteria criteria1 = issuesExample.createCriteria();
            criteria1.andOrderIdEqualTo(workOrder.getId());
            List<Issues> issues = issuesMapper.selectByExample(issuesExample);
            UserInfos userInfos1 = userInfosMapper.selectByPrimaryKey(issues.get(0).getUserId());
            specialEnvoyQueriesWorkOrdersDto.setUserName(userInfos1.getUserName());
            WorkOrderDetailsExample workOrderDetailsExample = new WorkOrderDetailsExample();
            WorkOrderDetailsExample.Criteria criteria2 = workOrderDetailsExample.createCriteria();
            criteria2.andOrderIdEqualTo(workOrder.getId());
            List<WorkOrderDetails> workOrderDetails = workOrderDetailsMapper.selectByExample(workOrderDetailsExample);
            specialEnvoyQueriesWorkOrdersDto.setDescription(workOrderDetails.get(0).getDescription());
            specialEnvoyQueriesWorkOrdersDto.setTimestamp(workOrderDetails.get(0).getTimestamp());
            specialEnvoyQueriesWorkOrdersDtos.add(specialEnvoyQueriesWorkOrdersDto);
        }
        return specialEnvoyQueriesWorkOrdersDtos;
    }

    @Override
    public void specialEnvoyOnlineStatement(specialEnvoyOnlineStatementParam param) {
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(param.getId());
        workOrders.setFeedback(param.getFeedback());
        workOrders.setCompletionDate(param.getCompletionDate());
//        SpecialAgents specialAgents = specialAgentsMapper.selectAgentById(workOrders.getAgentId());
//        specialAgents.setWorkState(0L);
//        specialAgentsMapper.updateByPrimaryKey(specialAgents);
        workOrdersMapper.updateByPrimaryKey(workOrders);
    }

    @Override
    public void startOnlineWorkOrder(Long id) {
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(id);
        workOrders.setWorkType(1L);
//        SpecialAgents specialAgents = specialAgentsMapper.selectAgentById(workOrders.getAgentId());
//        specialAgents.setWorkState(1L);
//        specialAgentsMapper.updateByPrimaryKey(specialAgents);
        workOrdersMapper.updateByPrimaryKey(workOrders);
    }

    @Override
    public void startOfflineWorkOrder(StartOfflineWorkOrderParam param) {
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(param.getId());
        workOrders.setWorkType(2L);
        workOrders.setExpectedDate(param.getExpectedDate());
//        SpecialAgents specialAgents = specialAgentsMapper.selectAgentById(workOrders.getAgentId());
//        specialAgents.setWorkState(1L);
//        specialAgentsMapper.updateByPrimaryKey(specialAgents);
        workOrdersMapper.updateByPrimaryKey(workOrders);
        if (!param.getAccompanyingId().isEmpty()){
            for (Long aLong : param.getAccompanyingId()) {//添加随行人员
                WorkEntourage workEntourage = new WorkEntourage();
                workEntourage.setAgentId(aLong);
                workEntourage.setWorkId(workOrders.getId());
                workEntourageMapper.insert(workEntourage);
            }
        }
    }

    @Override
    public PageInfo<pendingEvaluationWorkOrderDto> pendingEvaluationWorkOrder(pendingEvaluationWorkOrderParam param) throws Exception {
        // 开启分页
        PageHelper.startPage(param.getPageIndex() == null ? 1 : param.getPageIndex(),
                param.getPageSize() == null ? 5 : param.getPageSize());

        // 设置查询条件
        WorkOrdersExample workOrdersExample = new WorkOrdersExample();
        workOrdersExample.createCriteria()
                .andStateIdNotEqualTo(2L)
                .andUserIdEqualTo(param.getUserId())
                .andWorkResultEqualTo(2L);

        // 执行分页查询（注意，此时返回的 workOrders 已经是分页后的结果）
        List<WorkOrders> workOrders = workOrdersMapper.selectByExample(workOrdersExample);
//        if (workOrders.isEmpty()) {
//            throw new Exception("当前用户尚未有已完成提问数据");
//        }

        // 开始处理分页后的结果
        List<pendingEvaluationWorkOrderDto> dtoList = new ArrayList<>();
        for (WorkOrders workOrder : workOrders) {
            Issues issues = issuesMapper.selectByPrimaryKey(workOrder.getIssueId());
            UserInfos userInfos = userInfosMapper.selectByPrimaryKey(workOrder.getAgentId());

            // 将 WorkOrder 转换为 DTO
            pendingEvaluationWorkOrderDto dto = BeanUtil.toBean(workOrder, pendingEvaluationWorkOrderDto.class);

            // 设置特派员名称
            if (userInfos != null) {
                dto.setAgentName(userInfos.getUserName());
            }
            dto.setWorkTypeName(workOrder.getWorkType().longValue() == 1 ? "线上" : "线下");
            // 设置问题名称和描述
            IssueType issueType = issueTypeMapper.selectByPrimaryKey(workOrder.getIssueTypeId());
            dto.setIssueName(issueType.getIssueName());
            dto.setDescription(issues.getDescription());
            // 添加到 DTO 列表中
            dtoList.add(dto);
        }
        // 使用 PageInfo 封装分页结果，注意这里的 workOrders 是分页后的
        PageInfo<pendingEvaluationWorkOrderDto> pageInfo = new PageInfo<>(dtoList);
        // 设置总记录数和分页信息，确保前端能正确显示总页数和条数
        pageInfo.setTotal(new PageInfo<>(workOrders).getTotal());  // 保留总条数信息
        return pageInfo;
    }

    @Override
    public void confirmEvaluation(ConfirmEvaluationParam param) {
        System.out.println(param);
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(param.getId());
        workOrders.setEvaluate(param.getEvaluate());//满意度
        workOrders.setStateId(2L);//0.待评价1.已评价，修改为已评价
        if (workOrders.getAgentId()!=null){
            SpecialAgentsExample specialAgentsExample = new SpecialAgentsExample();
            specialAgentsExample.createCriteria().andUserIdEqualTo(workOrders.getAgentId());
            List<SpecialAgents> specialAgents = specialAgentsMapper.selectByExample(specialAgentsExample);
            System.out.println(111);
            specialAgents.get(0).setWorkState(Long.sum(specialAgents.get(0).getWorkState(), param.getEvaluate()));//修改状态为绩效评分
            specialAgentsMapper.updateByPrimaryKey(specialAgents.get(0));
        }
        System.out.println(workOrders);
        workOrdersMapper.updateByPrimaryKey(workOrders);
    }

    @Override
    public void theUserIsLookingForASpecialEnvoy(Long issuesId) {
        Issues issues = issuesMapper.selectByPrimaryKey(issuesId);
        issues.setResolvePeople(1L);//0知识库解决问题1特派员解决问题
        issuesMapper.updateByPrimaryKey(issues);
    }

    @Override
    public PageInfo<QueryQuestionsDto> queryQuestions(PageParam param,Long userId) throws Exception {
        // 开启分页
        PageHelper.startPage(param.getPageIndex() == null ? 1 : param.getPageIndex(),
                param.getPageSize() == null ? 5 : param.getPageSize());
        IssuesExample e = new IssuesExample();
        e.createCriteria().andUserIdEqualTo(userId).andIssueStateEqualTo(0L);
        List<Issues> issues = issuesMapper.selectByExample(e);
//        if (issues.isEmpty())throw new Exception("无问题");
        ArrayList<QueryQuestionsDto> queryQuestionsDtos = new ArrayList<>();
        for (Issues issue : issues) {
            QueryQuestionsDto queryQuestionsDto = BeanUtil.toBean(issue, QueryQuestionsDto.class);
            IssueType issueType = issueTypeMapper.selectByPrimaryKey(queryQuestionsDto.getIssueType());
            queryQuestionsDto.setIssueTypeName(issueType.getIssueName());
            UserInfos userInfos = userInfosMapper.selectByPrimaryKey(queryQuestionsDto.getUserId());
            queryQuestionsDto.setUserName(userInfos.getUserName());
            queryQuestionsDtos.add(queryQuestionsDto);
        }
        PageInfo<QueryQuestionsDto> queryQuestionsDtoPageInfo = new PageInfo<>(queryQuestionsDtos);
        queryQuestionsDtoPageInfo.setTotal(new PageInfo<>(issues).getTotal());
        return queryQuestionsDtoPageInfo;
    }

    @Override
    public void cancelTheIssue(CancelTheIssueParam param) {
        Issues issues = issuesMapper.selectByPrimaryKey(param.getIssuesId());
        issues.setIssueState(4L);//0.待办理1.处理中2.已解决3.未解决4.取消
        issues.setCancelStatus(0L);//0用户取消1特派员取消
        issues.setCancelReason(param.getCancelReason());//取消原因
        issues.setCancelExplain(param.getCancelExplain());//取消解释
        issuesMapper.updateByPrimaryKey(issues);
//        WorkOrdersExample example = new WorkOrdersExample();
//        example.createCriteria().andIssueIdEqualTo(param.getIssuesId());
//        List<WorkOrders> workOrders = workOrdersMapper.selectByExample(example);
//        if (!workOrders.isEmpty()){
//            workOrders.get(0).setWorkResult(0L);
//            workOrdersMapper.updateByPrimaryKey(workOrders.get(0));
//        }
    }

    @Override
    public PageInfo<QueryProcessingInProgressDto> queryProcessingInProgress(PageParam param, Long userId) {
        // 开启分页
        PageHelper.startPage(param.getPageIndex() == null ? 1 : param.getPageIndex(),
                param.getPageSize() == null ? 5 : param.getPageSize());
        IssuesExample e = new IssuesExample();
        e.createCriteria().andUserIdEqualTo(userId).andIssueStateEqualTo(1L);
        List<Issues> issues = issuesMapper.selectByExample(e);
//        if (issues.isEmpty())throw new Exception("无问题");
        ArrayList<QueryProcessingInProgressDto> queryQuestionsDtos = new ArrayList<>();
        for (Issues issue : issues) {
            QueryProcessingInProgressDto queryQuestionsDto = BeanUtil.toBean(issue, QueryProcessingInProgressDto.class);
            IssueType issueType = issueTypeMapper.selectByPrimaryKey(queryQuestionsDto.getIssueType());
            queryQuestionsDto.setIssueTypeName(issueType.getIssueName());
            UserInfos userInfos = userInfosMapper.selectByPrimaryKey(queryQuestionsDto.getUserId());
            queryQuestionsDto.setUserName(userInfos.getUserName());
            if (queryQuestionsDto.getAgentId()!=null){
                UserInfos agentInfo = userInfosMapper.selectByPrimaryKey(queryQuestionsDto.getAgentId());
                if(agentInfo!=null){
                    queryQuestionsDto.setAgentName(agentInfo.getUserName());
                }
            }
            WorkOrdersExample workOrdersExample = new WorkOrdersExample();
            workOrdersExample.createCriteria().andIssueIdEqualTo(issue.getId());
            List<WorkOrders> workOrders = workOrdersMapper.selectByExample(workOrdersExample);
            queryQuestionsDto.setWorkAddress(workOrders.get(0).getWorkAddress());
            queryQuestionsDto.setCreatedDate(workOrders.get(0).getCreatedDate());
            queryQuestionsDto.setSignInDate(workOrders.get(0).getSignInDate());
            queryQuestionsDto.setExpectedDate(workOrders.get(0).getExpectedDate());
            queryQuestionsDto.setWorkTypeName(workOrders.get(0).getWorkType()==1?"线上":"线下");
            queryQuestionsDtos.add(queryQuestionsDto);
        }
        PageInfo<QueryProcessingInProgressDto> queryQuestionsDtoPageInfo = new PageInfo<>(queryQuestionsDtos);
        queryQuestionsDtoPageInfo.setTotal(new PageInfo<>(issues).getTotal());
        return queryQuestionsDtoPageInfo;
    }

    @Override
    public PageInfo<AdminWorkOredeDto> adminselectWorkOrdes(AdminselectWorkOrdersParam param) {
        PageHelper.startPage(param.getPageIndex() == null ? 1 : param.getPageIndex(), param.getPageSize() == null ? 5 : param.getPageSize());
        List<AdminWorkOredeDto> adminWorkOredeDtos = workOrdersMapper.adminselectWorkOrdes(param.getIssueTypeId(),param.getStateId(),param.getOrderTitle());
        return new PageInfo<>(adminWorkOredeDtos);
    }

    @Override
    public void onlineCompletionOfWorkOrders(OnlineWorkOrderParam param) {
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(param.getId());
        workOrders.setCompletionDate(param.getCompletionDate());
        workOrders.setFeedback(param.getFeedback());
//        workOrders.setNumberOfTrainees(param.getNumberOfTrainees());
//        workOrders.setSolveTheProblem(param.getSolveTheProblem());
        workOrders.setWorkResult(2L);
        workOrders.setStateId(1L);//1待评价2已评价
        workOrders.setWorkType(1L);//1线上解决2线下解决
        Issues issues = issuesMapper.selectByPrimaryKey(workOrders.getIssueId());
        issues.setResolvePeople(1L);//0知识库解决问题1特派员解决问题
        issues.setIssueState(2L);//0.待办理1.处理中2.已解决3.未解决
//        SpecialAgents specialAgents = specialAgentsMapper.selectAgentById(workOrders.getAgentId());
//        specialAgents.setWorkState(0L);
//        specialAgentsMapper.updateByPrimaryKey(specialAgents);
        issuesMapper.updateByPrimaryKey(issues);
        workOrdersMapper.updateByPrimaryKey(workOrders);
    }

    @Override
    public void specialEnvoyCancelled(SpecialEnvoyCancelledParam param) {
        Issues issues = issuesMapper.selectByPrimaryKey(param.getIssuesId());
        issues.setIssueState(4L);//0.待办理1.处理中2.已解决3.未解决4.取消5.上报
        issues.setCancelStatus(1L);//0用户取消1特派员取消
        issues.setCancelReason(param.getCancelReason());//取消原因
        issues.setCancelExplain(param.getCancelExplain());//取消解释
        issuesMapper.updateByPrimaryKey(issues);
    }

    @Override
    public void reportToTheMunicipalBureau(ReportToTheMunicipalBureauParam param) {
        WorkOrders workOrders = workOrdersMapper.selectByPrimaryKey(param.getId());
        workOrders.setCancelExplain(param.getCancelExplain());
        workOrders.setWorkResult(3L);//0.取消处理1.处理中2.已解决3.上报
        Issues issues = issuesMapper.selectByPrimaryKey(workOrders.getIssueId());
        issues.setIssueState(5L);//0.待办理1.处理中2.已解决3.未解决4.取消
        issues.setCancelStatus(1L);//0用户取消1特派员取消
        issuesMapper.updateByPrimaryKey(issues);
        workOrdersMapper.updateByPrimaryKey(workOrders);
    }

}
